package com.ecommerce.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.ecommerce.common.BizException;
import com.ecommerce.common.ResultCode;
import com.ecommerce.product.entity.Product;
import com.ecommerce.product.entity.ProductPromotion;
import com.ecommerce.product.entity.ProductReview;
import com.ecommerce.product.entity.ProductSpec;
import com.ecommerce.product.repository.ProductRepository;
import com.ecommerce.product.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 商品服务实现类
 * 
 * @author ecommerce-team
 * @version 1.0.0
 */
@Service
@Transactional(readOnly = true)
public class ProductServiceImpl implements ProductService {
    
    private static final Logger log = LoggerFactory.getLogger(ProductServiceImpl.class);
    
    @Autowired
    private ProductRepository productRepository;
    
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    
    @Override
    public Product getProductById(Long id) {
        if (id == null || id <= 0) {
            throw new BizException(ResultCode.PARAM_ERROR.getCode(), "商品ID不能为空");
        }
        
        Optional<Product> productOpt = productRepository.findByIdAndStatusActive(id);
        if (!productOpt.isPresent()) {
            throw new BizException(ResultCode.PRODUCT_NOT_FOUND);
        }
        
        Product product = productOpt.get();
        
        // 处理商品图片列表
        if (StringUtils.hasText(product.getImages())) {
            try {
                List<String> imageList = JSON.parseArray(product.getImages(), String.class);
                product.setImageList(imageList);
            } catch (Exception e) {
                log.warn("解析商品图片失败: {}", e.getMessage());
                product.setImageList(new ArrayList<>());
            }
        }
        
        // 处理商品详情图列表
        if (StringUtils.hasText(product.getDetailImages())) {
            try {
                List<String> detailImageList = JSON.parseArray(product.getDetailImages(), String.class);
                product.setDetailImageList(detailImageList);
            } catch (Exception e) {
                log.warn("解析商品详情图失败: {}", e.getMessage());
                product.setDetailImageList(new ArrayList<>());
            }
        }
        
        // TODO: 查询商品规格、促销信息、评价等关联数据
        // 这里先返回模拟数据，后续可以通过关联查询获取真实数据
        product.setSpecs(getMockSpecs());
        product.setPromotions(getMockPromotions());
        product.setReviews(getMockReviews());
        
        return product;
    }
    
    @Override
    public Page<Product> getProductList(Pageable pageable) {
        Page<Product> productPage = productRepository.findProductsOrderByCreateTime(pageable);
        processProductList(productPage.getContent());
        return productPage;
    }
    
    @Override
    public Page<Product> getProductsByCategory(Long categoryId, Pageable pageable) {
        if (categoryId == null || categoryId <= 0) {
            throw new BizException(ResultCode.PARAM_ERROR.getCode(), "分类ID不能为空");
        }
        
        Page<Product> productPage = productRepository.findByCategoryId(categoryId, pageable);
        processProductList(productPage.getContent());
        return productPage;
    }
    
    @Override
    public Page<Product> getProductsByBrand(Long brandId, Pageable pageable) {
        if (brandId == null || brandId <= 0) {
            throw new BizException(ResultCode.PARAM_ERROR.getCode(), "品牌ID不能为空");
        }
        
        Page<Product> productPage = productRepository.findByBrandId(brandId, pageable);
        processProductList(productPage.getContent());
        return productPage;
    }
    
    @Override
    public Page<Product> getProductsByPriceRange(BigDecimal minPrice, BigDecimal maxPrice, Pageable pageable) {
        if (minPrice == null || maxPrice == null || minPrice.compareTo(maxPrice) > 0) {
            throw new BizException(ResultCode.PARAM_ERROR.getCode(), "价格区间参数错误");
        }
        
        Page<Product> productPage = productRepository.findByPriceRange(minPrice, maxPrice, pageable);
        processProductList(productPage.getContent());
        return productPage;
    }
    
    @Override
    public Page<Product> searchProducts(String keyword, Pageable pageable) {
        if (!StringUtils.hasText(keyword)) {
            throw new BizException(ResultCode.PARAM_ERROR.getCode(), "搜索关键词不能为空");
        }
        
        Page<Product> productPage = productRepository.searchByKeyword(keyword.trim(), pageable);
        processProductList(productPage.getContent());
        return productPage;
    }
    
    @Override
    public Page<Product> getRecommendProducts(Pageable pageable) {
        Page<Product> productPage = productRepository.findRecommendProducts(pageable);
        processProductList(productPage.getContent());
        return productPage;
    }
    
    @Override
    public Page<Product> getHotProducts(Pageable pageable) {
        Page<Product> productPage = productRepository.findHotProducts(pageable);
        processProductList(productPage.getContent());
        return productPage;
    }
    
    @Override
    public Page<Product> getNewProducts(Pageable pageable) {
        Page<Product> productPage = productRepository.findNewProducts(pageable);
        processProductList(productPage.getContent());
        return productPage;
    }
    
    @Override
    public Page<Product> getProductsBySort(String sortType, Pageable pageable) {
        if (!StringUtils.hasText(sortType)) {
            sortType = "time";
        }
        
        Page<Product> productPage;
        switch (sortType.toLowerCase()) {
            case "sales":
                productPage = productRepository.findProductsOrderBySales(pageable);
                break;
            case "price_asc":
                productPage = productRepository.findProductsOrderByPriceAsc(pageable);
                break;
            case "price_desc":
                productPage = productRepository.findProductsOrderByPriceDesc(pageable);
                break;
            case "time":
            default:
                productPage = productRepository.findProductsOrderByCreateTime(pageable);
                break;
        }
        
        processProductList(productPage.getContent());
        return productPage;
    }
    
    @Override
    public List<Product> getProductsByIds(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return new ArrayList<>();
        }
        
        List<Product> products = productRepository.findByIds(ids);
        processProductList(products);
        return products;
    }
    
    @Override
    public boolean checkStock(Long productId, Integer quantity) {
        if (productId == null || quantity == null || quantity <= 0) {
            return false;
        }
        
        Optional<Product> productOpt = productRepository.findByIdAndStatusActive(productId);
        if (!productOpt.isPresent()) {
            return false;
        }
        
        Product product = productOpt.get();
        return product.getStock() >= quantity;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean reduceStock(Long productId, Integer quantity) {
        if (productId == null || quantity == null || quantity <= 0) {
            return false;
        }
        
        Optional<Product> productOpt = productRepository.findByIdAndStatusActive(productId);
        if (!productOpt.isPresent()) {
            throw new BizException(ResultCode.PRODUCT_NOT_FOUND);
        }
        
        Product product = productOpt.get();
        if (product.getStock() < quantity) {
            throw new BizException(ResultCode.PRODUCT_STOCK_INSUFFICIENT);
        }
        
        product.setStock(product.getStock() - quantity);
        productRepository.save(product);
        
        log.info("商品库存扣减成功: productId={}, quantity={}, remainStock={}", 
                productId, quantity, product.getStock());
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean increaseStock(Long productId, Integer quantity) {
        if (productId == null || quantity == null || quantity <= 0) {
            return false;
        }
        
        Optional<Product> productOpt = productRepository.findByIdAndStatusActive(productId);
        if (!productOpt.isPresent()) {
            throw new BizException(ResultCode.PRODUCT_NOT_FOUND);
        }
        
        Product product = productOpt.get();
        product.setStock(product.getStock() + quantity);
        productRepository.save(product);
        
        log.info("商品库存增加成功: productId={}, quantity={}, currentStock={}", 
                productId, quantity, product.getStock());
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean increaseSales(Long productId, Integer quantity) {
        if (productId == null || quantity == null || quantity <= 0) {
            return false;
        }
        
        Optional<Product> productOpt = productRepository.findByIdAndStatusActive(productId);
        if (!productOpt.isPresent()) {
            throw new BizException(ResultCode.PRODUCT_NOT_FOUND);
        }
        
        Product product = productOpt.get();
        int currentSales = product.getSales() != null ? product.getSales() : 0;
        product.setSales(currentSales + quantity);
        productRepository.save(product);
        
        log.info("商品销量增加成功: productId={}, quantity={}, currentSales={}", 
                productId, quantity, product.getSales());
        return true;
    }
    
    @Override
    public Long getProductCount() {
        return productRepository.countActiveProducts();
    }
    
    @Override
    public Long getProductCountByCategory(Long categoryId) {
        if (categoryId == null || categoryId <= 0) {
            return 0L;
        }
        return productRepository.countByCategoryId(categoryId);
    }
    
    @Override
    public List<Product> getLowStockProducts(Integer threshold) {
        if (threshold == null || threshold < 0) {
            threshold = 10; // 默认阈值
        }
        return productRepository.findLowStockProducts(threshold);
    }
    
    /**
     * 处理商品列表数据
     */
    private void processProductList(List<Product> products) {
        if (products == null || products.isEmpty()) {
            return;
        }
        
        for (Product product : products) {
            // 处理商品图片列表
            if (StringUtils.hasText(product.getImages())) {
                try {
                    List<String> imageList = JSON.parseArray(product.getImages(), String.class);
                    product.setImageList(imageList);
                } catch (Exception e) {
                    log.warn("解析商品图片失败: {}", e.getMessage());
                    product.setImageList(new ArrayList<>());
                }
            }
        }
    }
    
    /**
     * 获取模拟规格数据
     */
    private List<ProductSpec> getMockSpecs() {
        List<ProductSpec> specs = new ArrayList<>();
        
        ProductSpec colorSpec = new ProductSpec();
        colorSpec.setName("颜色");
        List<String> colors = new ArrayList<>();
        colors.add("星空黑");
        colors.add("珍珠白");
        colors.add("极光蓝");
        colors.add("玫瑰金");
        colorSpec.setValueList(colors);
        specs.add(colorSpec);
        
        ProductSpec memorySpec = new ProductSpec();
        memorySpec.setName("内存");
        List<String> memories = new ArrayList<>();
        memories.add("128GB");
        memories.add("256GB");
        memories.add("512GB");
        memorySpec.setValueList(memories);
        specs.add(memorySpec);
        
        return specs;
    }
    
    /**
     * 获取模拟促销数据
     */
    private List<ProductPromotion> getMockPromotions() {
        List<ProductPromotion> promotions = new ArrayList<>();
        
        ProductPromotion promotion1 = new ProductPromotion();
        promotion1.setType("满减");
        promotion1.setText("满299减30，满599减80");
        promotions.add(promotion1);
        
        ProductPromotion promotion2 = new ProductPromotion();
        promotion2.setType("优惠券");
        promotion2.setText("领取50元优惠券");
        promotions.add(promotion2);
        
        return promotions;
    }
    
    /**
     * 获取模拟评价数据
     */
    private List<ProductReview> getMockReviews() {
        List<ProductReview> reviews = new ArrayList<>();
        
        ProductReview review1 = new ProductReview();
        review1.setUsername("用户***123");
        review1.setAvatar("https://ai-public.mastergo.com/ai/img_res/0bb0de76012a21317548d7c11e047bf6.jpg");
        review1.setRating(5);
        review1.setContent("手机很不错，屏幕清晰，电池续航能力强，值得购买！");
        review1.setTime("2023-12-01");
        review1.setImageList(new ArrayList<>());
        reviews.add(review1);
        
        ProductReview review2 = new ProductReview();
        review2.setUsername("用户***456");
        review2.setAvatar("https://ai-public.mastergo.com/ai/img_res/fa900c94f52fed4589e4b9eb9ea81fd7.jpg");
        review2.setRating(4);
        review2.setContent("整体满意，性价比很高，就是充电器有点重。");
        review2.setTime("2023-11-28");
        List<String> images = new ArrayList<>();
        images.add("https://ai-public.mastergo.com/ai/img_res/ffab28ea4d2c605e301b41dc31a81632.jpg");
        review2.setImageList(images);
        reviews.add(review2);
        
        return reviews;
    }
}